package com.bluesky.drcp.business.service;

import netscape.ldap.LDAPConnection;
import netscape.ldap.LDAPException;

public class LdapAuthenticationService implements AuthenticationService {

	private String hostNames;
	private String domainName;
	private int port = 3268;

	
	public boolean login(String userId, String password) {
		
		if (userId == null || password == null) {
			return false;
		}

		String host = null;
		LDAPConnection ld = new LDAPConnection();

		String[] hostlist = hostNames.split(",");
		boolean havegoodhost = false;
		for (int i = 0; i < hostlist.length; i++) {
			try {
				host = hostlist[i];
				ld.connect(host, port);
				ld.disconnect();
				havegoodhost = true;
				break;
			} catch (LDAPException e) {
				// System.out.println("Error: -- " + host );
				// System.out.println("Error code:" + e.getLDAPResultCode());
				// System.out.println("Error desc:" + e.toString());
			}
		}

		if (havegoodhost) {
			try {
				userId = userId + "@" + domainName;
				ld.connect(host, port, userId, password);

				return true;
			} catch (LDAPException e) {

				// System.out.println("Error code:" + e.getLDAPResultCode());
				// System.out.println("Error desc:" + e.toString());
			} finally {
				// disconnect
				if ((ld != null) && ld.isConnected()) {
					try {
						ld.disconnect();
					} catch (LDAPException e) {
						// System.out.println( e.toString() );
					}
				}//
			}// finally
		} else {

		}
		return false;
	}

	

	public String getHostNames() {
		return hostNames;
	}



	public void setHostNames(String hostNames) {
		this.hostNames = hostNames;
	}



	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public String getDomainName() {
		return domainName;
	}

	public void setDomainName(String domainName) {
		this.domainName = domainName;
	}

}
